package com.s2.m.btchat;

import java.io.IOException;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;

/**
 *
 * @author Samik Saha
 */
public class Server implements Runnable {

    /**
     * Chat Service UUID
     */
    private static final UUID CHAT_SERVICE_ID =
            new UUID("f631b1e0842211deb89a0002a5d5c51b", false);
    /**
     * The attribute id of the record item for profile values
     */
    //private static final int PROFILE_ATTRIBUTE_ID = 0x4321;
    /**
     * Keeps the local device reference.
     */
    private LocalDevice localDevice;
    /**
     * Accepts new connections.
     */
    private StreamConnectionNotifier notifier;
    /**
     * Keeps the information about this server.
     */
    private ServiceRecord record;
    /**
     * Keeps the parent Reference
     */
    private boolean endNow = false;
    private static boolean running = false;

    public void run() {
        try {
            //get a local device instance
            localDevice = LocalDevice.getLocalDevice();

            // set we are discoverable
            if (!localDevice.setDiscoverable(DiscoveryAgent.GIAC)) {
            }

            //prepare url to create a notifier
            String url = "btspp://localhost:" + CHAT_SERVICE_ID.toString() +
                    ";name=Chat Service;authorize=false";

            //create notifier
            notifier = (StreamConnectionNotifier) Connector.open(url.toString());
            running = true;
            BTChat.getInstance().chatServiceStarted(true);
            // and remember the service record for the later updates
            record = localDevice.getRecord(notifier);

            // Create a spacial attribute with profile values
            //DataElement profile = new DataElement(DataElement.DATSEQ);
            //record.setAttributeValue(PROFILE_ATTRIBUTE_ID, profile);

            updateServiceRecord();
        } catch (Exception ex) {
            BTChat.getInstance().chatServiceStarted(false);
            ex.printStackTrace();
        }

        while (!endNow) {
            StreamConnection conn = null;

            try {
                conn = notifier.acceptAndOpen();
            } catch (IOException ex) {
                ex.printStackTrace();
                continue;
            }
            if (conn != null) {
                //Create a new ChatHandler to handle this connection
                new ClientHandler(conn);
            }
        }
    }

    void destroy() {
        endNow = true;
        running = false;
        // finalize notifier work
        if (notifier != null) {
            try {
                notifier.close();
            } catch (IOException e) {
            } // ignore
        }
    }

    public static boolean isRunning() {
        return running;
    }

    public void updateServiceRecord() {
        //TODO: Use a single attribute to store all the profile values


        DataElement userName = new DataElement(DataElement.STRING,
                MyProfile.getUsername());
        record.setAttributeValue(0x4320, userName);

        DataElement fullName = new DataElement(DataElement.STRING,
                MyProfile.getFullName());
        record.setAttributeValue(0x4321, fullName);

        DataElement aboutMe = new DataElement(DataElement.STRING,
                MyProfile.getAboutMe());
        record.setAttributeValue(0x4322, aboutMe);

        DataElement age = new DataElement(DataElement.STRING,
                MyProfile.getAge());
        record.setAttributeValue(0x4323, age);

        DataElement sex = new DataElement(DataElement.STRING,
                MyProfile.getSex());
        record.setAttributeValue(0x4324, sex);

        DataElement profession = new DataElement(DataElement.STRING,
                MyProfile.getProfession());
        record.setAttributeValue(0x4325, profession);
        try {
            localDevice.updateRecord(record);
        } catch (ServiceRegistrationException ex) {
            ex.printStackTrace();
        }
    }
}
